package net.awpspace.mobile.management.book;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.midlet.MIDlet;

import net.awpspace.mobile.form.BaseForm;

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Container;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;

public class ViewBook extends BaseForm {

	private BookModel model;

	private Command cmdEdit;

	public ViewBook(MIDlet app, BaseForm parent, BookModel model) {
		super(app, parent);
		this.model = model;

		setTitle(model.getName());
		setLayout(new BorderLayout());

		Container ctn = new Container(new BoxLayout(BoxLayout.Y_AXIS));
		ctn.addComponent(new Label("ID: " + model.getId()));
		ctn.addComponent(new Label("Author: " + model.getAuthor()));

		try {
			StreamConnection streamConnection = (StreamConnection) Connector
					.open(model.getImage());
			Image image = Image.createImage(streamConnection.openInputStream());
			streamConnection.close();
			if (image != null) {
				ctn.addComponent(new Label(image));
			}
		} catch (IOException e) {
			ctn.addComponent(new Label("Could not load image"));
		}

		ctn.addComponent(new Label(model.getDescription()));
		addComponent(BorderLayout.CENTER, ctn);

		cmdEdit = new Command("Edit");
		addComponent(BorderLayout.SOUTH, new Button(cmdEdit));
	}

	protected void processCommand(ActionEvent e) {
		if (e.getCommand().equals(cmdEdit)) {
			new ViewInsert(app, this, model).show();
		}
	}
}
